import advList from '$v/advList'
import {
    isloginRequest
} from '$a/admin'
import {
    addAdvRequest,
    advListRequest
} from '../api/adv'
const getAllAdvList = async (res) => {
    let findre = null
    //发送请求
    try {
      //一旦return 则当前函数返回一个promise实例 值为当前await的返回值
      findre = await advListRequest();
    } catch (e) {
      alert("查询出现异常" + e.message);
      //判断是否是权限异常
      if (!e.isLogin) {
        return router.go("/login");
      }
    }
    res.render(advList({
        advList: findre
    }))
  
  }
export default async (req, res) => {
    try {
        await isloginRequest()
    } catch (e) {
        alert(e.message)
        //判断是否是权限异常
        if (!e.isLogin) {
            return router.go("/login");
        }
    }
    getAllAdvList(res)
    document.onclick = async function (e) {
        if (e.target.id === 'adv-save') {
            const myForm = new FormData(document.advForm)
            console.log(myForm);
            if (!myForm.get('advTitle') || !myForm.get("advType") || !myForm.get("advOrder") || !myForm.get("advPic")){
                return alert("添加的内容不能有空的！！！！")
            }
            try {
                await addAdvRequest(myForm)
                alert("添加广告成功")
                //关闭添加广告的弹窗
                document.getElementById("addClose").click();

                //把预览的img隐藏
                const oPreImg = document.getElementById('preImg');
                oPreImg.style.display = "none"

                //清空表单
                document.advForm.reset();
                getAllAdvList(res)
            } catch (e) {
                alert("添加广告异常" + e.message);
                //判断是否是权限异常
                if (!e.isLogin) {
                    //关闭添加广告的弹窗再跳转
                    document.getElementById("addClose").click();
                    return router.go("/login");
                }
            }
        }
        
    }
    document.onchange = function (e) {
        if (e.target.id === "advPic") {
            const reader = new FileReader();
            reader.readAsDataURL(e.target.files[0])
            reader.onload = function (e) {
                // console.log(e.target.result);
                //把当前的读取的base64格式 给到img
                const oPreImg = document.getElementById('preImg');
                oPreImg.src = e.target.result;
                oPreImg.style.display = "block"
            }
        }
    }
}